<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\shiyao;

use app\common\model\shiyao\ProjectPay as PayLogModel;
use app\common\service\store\User as UserService;
use think\facade\Db;

/**
 * 申办方模型
 * Class StoreUser
 * @package app\store\model
 */
class PayLog extends PayLogModel {

	public function getListAll(array $param) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['logids' => [], 'pm_status' => -1, 'pi_status' => -1, 'company_id' => '', 'testee_id' => '', 'center_id' => '', 'project_id' => '', 'search' => '', 'betweenTimePay' => [], 'betweenTime' => [], 'payStatus' => -1, 'payStatusPm' => -1]);
		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 支付时间
		if (!empty($params['betweenTimePay'])) {
			$times = between_time($params['betweenTimePay']);
			$filter[] = ['p.pay_time', '>=', $times['start_time']];
			$filter[] = ['p.pay_time', '<', $times['end_time'] + 86400];
		}

		if ($params['payStatus'] > 0) {

			if ($params['payStatus'] == 3) {
				//全部
				$filter[] = ['p.pay_status', 'in', [1, 2]];
				if ($params['payStatusPm'] == -1) {
					$filter[] = ['p.pay_status_pm', 'in', [1, 2]];
				}

			} elseif ($params['payStatus'] == 4) {
				$filter[] = ['p.pay_status', '=', 1];
				$filter[] = ['p.pay_status_pm', '=', 1];

			} else {

				$filter[] = ['p.pay_status', '=', $params['payStatus']];
			}

		}

		if ($params['payStatusPm'] > -1) {
			$filter[] = ['p.pay_status_pm', '=', $params['payStatusPm']];
		}

		if ($params['pm_status'] == 0) {
			//pm待审核
			$query->where('p.pm_status', '=', 0);
			$query->where('p.pi_status', '=', 1);
			$query->where('p.status', '=', 10);
		} elseif ($params['pm_status'] > 0) {
			$query->where('p.pm_status', '=', $params['pm_status']);
		}

		!empty($params['center_id']) && $query->where('p.center_id', '=', $params['center_id']);
		!empty($params['project_id']) && $query->where('p.project_id', '=', $params['project_id']);
		!empty($params['testee_id']) && $query->where('p.testee_id', '=', $params['testee_id']);

		if ($params['payStatus'] == 4 || $params['payStatus'] == 2) {
			$order = ['p.pay_audit_time' => 'desc'];
		} else {
			$order = ['pr.project_code' => 'asc', 'center.center_code' => 'asc', 't.code' => 'asc'];
		}

		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];

		if ($store_user['company_id'] > 0) {
			$query->where('c.company_id', '=', $store_user['company_id']);

		}

		if (!empty($params['logids'])) {
			$filter[] = ['p.id', 'in', $params['logids']];
		}

		!empty($params['company_id']) && $query->where('c.company_id', '=', $params['company_id']);

		// 关键词搜索
		!empty($params['search']) && $query->where('pr.project_name|pr.project_code|c.company_name|center.center_code|t.code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$lists = $query->alias('p')->with(['center.pm', 'project.company', 'testee',
			'refer', 'images', 'openImages', 'admin', 'payee', 'auditPm', 'auditPi'])
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_project_pay_category category', 'category.category_id=p.type')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->join('shiyao_project_center center', 'center.id=p.center_id')
			->join('shiyao_project_center_testee t', 't.testee_id=p.testee_id')
			->field('p.*,pr.project_name,pr.project_code,c.company_name,center.center_name,center.center_code,t.code as testee_code,t.name_suoxie,t.name as testee_name,category.category_name')
			->where($filter)
			->where('p.is_delete', '=', '0')
			->order($order)
			->select()->toArray();

		foreach ($lists as $key => $list) {
			$lists[$key]['cycle'] = $list['is_out'] ? '计划外访视：' . $list['date'] : $list['visit_cycle'];
			$lists[$key]['center_label'] = $list['center_code'] . '/' . $list['center_name'];
			$lists[$key]['center_pm'] = $list['center']['pm'] ? $list['center']['pm']['nick_name'] : '';
			$lists[$key]['pay_admin_name'] = $list['admin'] ? $list['admin']['real_name'] : ''; //审批人

			$payee = $list['payee_id'] > 0 ? $list['payee']['nick_name'] : $list['payee'];

			$lists[$key]['payee'] = $list['payee_role'] == 0 ? $list['testee_name'] : $payee;
			if ($list['payee_id'] > 0) {
				$payee= $list['payee'];
				$lists[$key]['pay_info'] = $payee['nick_name'] . ';' . $payee['bank_num'] . ';' . $payee['bank_name'];

			} else {
				$lists[$key]['pay_info'] = $list['bank_real_name'] . ';' . $list['bank_num'] . ';' . $list['bank_name'];
			}

			$auditDate = '';
			if ($list['pi_status'] > 0) {
				$auditDate .= '研究者审批：' . $list['audit_time_pi'];
			}
			if ($list['pm_status'] > 0) {
				$auditDate .= ';PM审批：' . $list['audit_time_pm'];
			}
			$lists[$key]['auditDate'] = $auditDate;
			$lists[$key]['refer_name'] = $list['refer']['nick_name'];
			$lists[$key]['audit_pi'] = $list['auditPi'] ? $list['auditPi']['nick_name'] : '';
			$lists[$key]['audit_pm'] = $list['auditPm'] ? $list['auditPm']['nick_name'] : '';
			$lists[$key]['pm'] = $list['center']['pm'] ? $list['center']['pm']['nick_name'] : '';
		}
		return $lists;
	}

	public function getList($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['pm_status' => -1, 'pi_status' => -1, 'company_id' => -1, 'testee_id' => '', 'center_id' => '', 'project_id' => -1, 'search' => '', 'betweenTimePay' => [], 'betweenTime' => [], 'payStatus' => -1, 'payStatusPm' => -1, 'status' => -1]);
		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		// 支付时间
		if (!empty($params['betweenTimePay'])) {
			$times = between_time($params['betweenTimePay']);
			$filter[] = ['p.pay_time', '>=', $times['start_time']];
			$filter[] = ['p.pay_time', '<', $times['end_time'] + 86400];
		}

		if ($params['payStatus'] > 0) {

			if ($params['payStatus'] == 3) {
				//全部
				$filter[] = ['p.pay_status', 'in', [1, 2, 3]];
				if ($params['payStatusPm'] == -1) {
					$filter[] = ['p.pay_status_pm', 'in', [1, 2]];
				}

			} elseif ($params['payStatus'] == 4) {
				$filter[] = ['p.pay_status', '=', 1];
				$filter[] = ['p.pay_status_pm', '=', 1];
				$filter[] = ['p.pay_status_admin', '=', 0]; //待付款

			} else {

				$filter[] = ['p.pay_status', '=', $params['payStatus']];
			}

		}

		if ($params['payStatus'] == 4) {
			$order = ['p.pay_audit_time' => 'desc'];
		} else {
			$order = ['pr.project_code' => 'asc', 'center.center_code' => 'asc', 't.code' => 'asc'];
		}

		if ($params['payStatusPm'] > -1) {
			$filter[] = ['p.pay_status_pm', '=', $params['payStatusPm']];
		}

		if ($params['pm_status'] == 0) {
			//pm待审核

			$filter[] = ['p.pm_status', '=', 0];
			$filter[] = ['p.pi_status', '=', 1];
			$filter[] = ['p.status', '=', 10];
		} elseif ($params['pm_status'] > 0) {

			$filter[] = ['p.pm_status', '=', $params['pm_status']];
		}

		//数据统计
		if ($params['status'] > -1) {
			$status = $params['status'];
			if (in_array($status, [10, 21, 30])) {
				//10待审核，21支付成功，30撤销
				$filter[] = ['p.status', '=', $status];
			}
			if ($status == 20) {
				//支付审批中
				$filter[] = ['p.status', '=', $status];
				$filter[] = ['p.pay_status_pm', '=', 0];

			}
			if ($status == 101) {
				//中心通过

				$filter[] = ['p.pi_status', '=', 1];

			}
			if ($status == 102) {
				//中心拒绝
				$filter[] = ['p.pi_status', '=', 2];

			}
			if ($status == 103) {
				//申办方通过
				$filter[] = ['p.pm_status', '=', 1];

			}
			if ($status == 104) {
				//申办方拒绝
				$filter[] = ['p.pm_status', '=', 2];

			}

			if ($status == 201) {
				//待付款
				$filter[] = ['p.pay_status_pm', '=', 1];
				$filter[] = ['p.pay_status_admin', '=', 0];

			}
			if ($status == 202) {
				//支付审批拒绝
				$filter[] = ['p.pay_status_pm', '=', 2];

			}

			if ($status == 203) {
				//支付申请错误
				$filter[] = ['p.pay_status_admin', '=', 2];

			}

		}

		!empty($params['center_id']) && $filter[] = ['p.center_id', '=', $params['center_id']];
		$params['project_id'] > 0 && $filter[] = ['p.project_id', '=', $params['project_id']];
		!empty($params['testee_id']) && $filter[] = ['p.testee_id', '=', $params['testee_id']];

		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];

		if ($store_user['company_id'] > 0) {

			$filter[] = ['c.company_id', '=', $store_user['company_id']];
		}

		$params['company_id'] > 0 && $filter[] = ['c.company_id', '=', $params['company_id']];

		//根据角色筛选
		$role = Db::name('store_user_role')->where('role_id', 'in', [10006, 10009])
			->where('store_user_id', $store_user['store_user_id'])->find();

		if ($role || $store_user['store_user_id'] == 10001) {

		} else {

			$user = Db::name('user')->where('mobile', $store_user['user_name'])->find();

			//审批人员
			$userId = $user['user_id'];
			$centerIds = Db::name('shiyao_project_center_pm')
				->where('pm_id', $userId)
				->where('center_id', $params['center_id'])
				->group('center_id')->select()->toArray();
			$centerIds = array_column($centerIds, 'center_id');

			//自己添加的项目
			$pmcenter = Db::name('shiyao_project_center')->where('id', $params['center_id'])
				->where('pm_id', $userId)->field('id')->select()->toArray();
			$centerIds2 = array_column($pmcenter, 'id');
			$newcenterIds = array_merge($centerIds, $centerIds2);

			if ($newcenterIds) {

				$filter[] = ['p.center_id', 'in', $newcenterIds];
			} else {

				//没有权限，设置空
				$filter[] = ['p.center_id', '=', -1];
				// if ($project && $project['is_share'] == 0) {

				// 	//是否信息共享

				// 	if ($user) {
				// 		$query->where('p.pm_id|p.pm_id_xiezhu', '=', $user['user_id']);
				// 	}
				// }

			}

		}

		// 关键词搜索
		!empty($params['search']) && $query->where('pr.project_name|pr.project_code|c.company_name|center.center_code|t.code|center.center_name', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')->with(['center.pm', 'project.company', 'pm.pm', 'testee', 'images.file', 'openImages.file', 'category', 'refer', 'auditPm', 'auditPi', 'admin', 'adminPay', 'payee.idcard1'])
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->join('user u', 'u.user_id=pr.pm_id')
			->join('shiyao_project_center center', 'center.id=p.center_id')
			->join('shiyao_project_center_testee t', 't.testee_id=p.testee_id')
			->field('p.*,u.nick_name,c.company_name')
			->where($filter)
			->where('p.is_delete', '=', '0')
			->order($order)
			->paginate(15);

		$total_money = $this->alias('p')
			->join('shiyao_project pr', 'pr.project_id=p.project_id')
			->join('shiyao_company c', 'c.company_id=pr.company_id')
			->join('user u', 'u.user_id=pr.pm_id')
			->join('shiyao_project_center center', 'center.id=p.center_id')
			->join('shiyao_project_center_testee t', 't.testee_id=p.testee_id')
			->where($filter)
			->where('p.is_delete', '=', '0')
			->sum('money');
		$data['list'] = $list;
		$data['total_money'] = $total_money;
		return $data;
	}
	/**
	 * 支付
	 * @param array $goodsIds 商品id集
	 * @param bool $state 为true表示上架
	 * @return bool|false
	 */
	public function setStatus($companyId, array $logIds): bool {

		// 批量更新记录
		$money = 0;
		foreach ($logIds as $key => $value) {

			$log = Db::name('shiyao_project_pay_log')->where('id', $value)->field('money,project_id')->find();
			$projectId = $log['project_id'];
			$money += $log['money'];

		}

		$company = Db::name('shiyao_company')->where('company_id', $companyId)->find();
		if ($company['type'] == 2) {
			$project = Db::name('shiyao_project')->where('project_id', $projectId)->where('company_id', $companyId)->find();
			//项目资金池
			if ($money > $project['balance']) {
				$this->error = '项目余额不足';
				return false;
			}

			Db::name('shiyao_project')->where('project_id', $project['project_id'])
				->inc('fee', $money)->update();

			Db::name('shiyao_project')->where('project_id', $project['project_id'])
				->dec('balance', $money)->update();

		} else {

			if ($money > $company['money_total']) {
				$this->error = '余额不足';
				return false;
			}

			Db::name('shiyao_company')->where('company_id', $companyId)
				->inc('fee_total', $money)->update();

			Db::name('shiyao_company')->where('company_id', $companyId)
				->dec('money_total', $money)->update();
		}

		//余额记录

		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		$data['ids'] = implode(',', $logIds);
		$data['scene'] = $money > 0 ? 20 : 40;
		$data['money'] = $money;
		$data['company_id'] = $companyId;
		$data['create_time'] = time();
		$data['remark'] = '订单支付';
		$data['describe'] = '后台管理员[' . $store_user['user_name'] . ']操作';
		$data['store_id'] = self::$storeId;
		Db::name('shiyao_company_balance_log')->insert($data);

		return static::updateBase(['pay_status' => 2, 'pay_time' => time(), 'status' => 21], [['id', 'in', $logIds]]);
	}

	/**
	 * pm-审核
	 * @param array $goodsIds 商品id集
	 * @param bool $state 为true表示上架
	 * @return bool|false
	 */
	public function setAudit(array $logIds, $state, $reason): bool {

		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		$user = Db::name('user')->where('mobile', $store_user['user_name'])->find();
		$userId = 0;
		if ($user) {
			$userId = $user['user_id'];
		}
		if ($state) {
			// 批量更新记录

			return static::updateBase(['pm_status' => 1, 'status' => 11, 'audit_pm_id' => $userId, 'audit_time_pm' => time()], [['id', 'in', $logIds]]);
		} else {
			// 批量更新记录

			return static::updateBase(['pm_status' => 2, 'status' => 12, 'audit_pm_id' => $userId,
				'reason' => $reason, 'audit_time_pm' => time()], [['id', 'in', $logIds]]);
		}

	}

	/**
	 * pm-财务审核
	 * @param array $goodsIds 商品id集
	 * @param bool $state 为true表示上架
	 * @return bool|false
	 */
	public function setAuditPay(array $logIds, $state, $reason = ''): bool {
		// 批量更新记录
		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		return static::updateBase(['pay_status_pm' => $state, 'admin_id' => $store_user['store_user_id'],
			'pay_audit_time' => time(), 'pay_reason' => $reason], [['id', 'in', $logIds], ['pay_status_pm', '=', 0]]);

	}
/**
 * 总后台-拒绝付款
 * @param array $goodsIds 商品id集
 * @param bool $state 为true表示上架
 * @return bool|false
 */
	public function setRejectPay(array $logIds, $state, $reason = ''): bool {

		// 批量更新记录
		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];

		return static::updateBase(['pay_status_admin' => 2, 'pay_status' => 3, 'admin_id_pay' => $store_user['store_user_id'],
			'pay_time' => time(), 'pay_reason' => $reason], [['id', 'in', $logIds]]);

	}
	/**
	 * 新增记录
	 * @param array $data
	 * @return bool
	 */
	public function add(array $data) {

		$data['store_id'] = self::$storeId;

		// 事务处理
		$this->transaction(function () use ($data) {
			// 新增
			$this->save($data);

		});
		return true;
	}

	/**
	 * 更新记录
	 * @param array $data
	 * @return bool
	 */
	public function edit(array $data) {

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	/**
	 * 软删除
	 * @return false|int
	 */
	public function setDelete(array $logIds) {

		$this->where('id', 'in', $logIds)->update(['is_delete' => 1]);
		// 批量更新记录
		return true;

	}
	public static function detail(int $PayLogId) {

		$detail = self::get(['id' => $PayLogId]);

		return $detail;
	}

}
